package com.weme.common.ext

import android.text.TextUtils
import android.util.Log
import android.widget.ImageView
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.jeremyliao.liveeventbus.LiveEventBus
import com.osom.proto.message.Brocast
import com.weme.chat.bean.CallMessage
import com.weme.common.activity.CallActivity
import com.weme.common.activity.CallOperationType
import com.weme.common.arouter.ARouterHelper
import com.weme.common.arouter.LiveRoomBean
import com.weme.common.dialog.PermissingDialog
import com.weme.common.network.*
import com.weme.common.util.*
import dev.kratos.api.im_server.v1.*
import dev.kratos.api.user_server.v1.GetAlbumReply
import dev.kratos.api.user_server.v1.Users
import io.agora.chat.BuildConfig
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class CallViewModeExt {}

fun CallActivity.setModeView(){
 LiveEventBus.get<Any>(Brocast.BrocastId.CMD_MATCH_ANSWER.name).observe(this) {
        if (it is Brocast.MatchMessage) { //视频应答
            val isDenied = mutableListOf<String>(Permission.RECORD_AUDIO, Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE).all { XXPermissions.isGranted(this, it) }
            if (isDenied) {
                ARouterHelper.navigateToLiveRoomActivity(this, LiveRoomBean(rtcToken = it.matchedUser.rtcToken, userId = it.matchedUser.uid, chatRoomId = it.chatRoomId, channelId = it.channelId, channelName = it.channelName, isIncoming = callOperationType == CallOperationType.INCOMING_VIDEO, matchMessage = it))
                getViewBind().countdownProgressBar.stopCountDown()
                finish()//跳转直播间 不用toast和发im消息 直接关闭
            } else {
                val permissingDialog = PermissingDialog(this, mutableListOf(Permission.RECORD_AUDIO, Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE)) {
                    ARouterHelper.navigateToLiveRoomActivity(this, LiveRoomBean(rtcToken = it.matchedUser.rtcToken, userId = it.matchedUser.uid, chatRoomId = it.chatRoomId, channelId = it.channelId, channelName = it.channelName, isIncoming = callOperationType == CallOperationType.INCOMING_VIDEO, matchMessage = it))
                    getViewBind().countdownProgressBar.stopCountDown()
                    finish()//跳转直播间 不用toast和发im消息 直接关闭
                }
                permissingDialog.show(this.supportFragmentManager, "")
            }
        }

    }

 LiveEventBus.get<Any>(LiveConfig.NET_WORK_LIVE).observe(this) { //这个挂断是主动发起的挂断
        if (it is HangUpVideoReply) { //主动挂断成功  呼入提示
            if (callOperationType == CallOperationType.INCOMING_VIDEO) {
                showToast(resources.getString(com.example.resources.R.string.call_canceled))
            }
            onBackPressedCallback.handleOnBackPressed()
        }
    }

 LiveEventBus.get<Any>(LiveConfig.NET_WORK_CALL).observe(this) { //感觉没用MatchCancelReply
        if (it is MatchCancelReply) { //匹配取消 通话已经挂断 直接关闭就可
            onBackPressedCallback.handleOnBackPressed()
        }else //未订阅
        if (it == ERROR_CODE_NOT_SUBSCRIBE) {
            callType = 1
            val callWaitTime = AppMkHelper.decodeInt(CALL_WAIT_TIME)
            countdownJob = CoroutineScope(Dispatchers.Main).launch {
                delay((callWaitTime).toLong() * 1000)
                runnable.run()
            }


        }else //用户繁忙
        if (it == ERROR_CODE_CALLED_BUSY) {
            callType = 0
            val callWaitTime = AppMkHelper.decodeInt(CALL_WAIT_TIME)
            countdownJob = CoroutineScope(Dispatchers.Main).launch {
                delay((callWaitTime).toLong() * 1000)
                runnable.run()
            }
        }else //余额不足
        if (it == ERROR_CODE_CALL_BALANCE_NOT_ENOUGH) {
            callType = 2
            val callWaitTime = AppMkHelper.decodeInt(CALL_WAIT_TIME)
            countdownJob = CoroutineScope(Dispatchers.Main).launch {
                delay((callWaitTime).toLong() * 1000)
                runnable.run()
            }
        }else
        if (it == ERROR_CODE_ANSWER_BALANCE_NOT_ENOUGH) {
            callType = 3
            val callWaitTime = AppMkHelper.decodeInt(CALL_WAIT_TIME)
            countdownJob = CoroutineScope(Dispatchers.Main).launch {
                delay((callWaitTime).toLong() * 1000)
                runnable.run()
            }
        }else
        if (it is AnswerVideoReply) {
            if (BuildConfig.DEBUG) {
                showToast("接听电话")
            }
            ARouterHelper.navigateToLiveRoomActivity(this@setModeView, LiveRoomBean(rtcToken = it.token, userId = videoCallMessage!!.caller.uid, chatRoomId = it.chatRoomId, channelName = it.channelName, channelId = it.channelId, isIncoming = callOperationType == CallOperationType.INCOMING_VIDEO))
            getViewBind().countdownProgressBar.stopCountDown()
            finish()//接听电话   不发消息不需要toast
        }else
        if (it is Brocast.VideoCallMessage) {
            if (BuildConfig.DEBUG) {
                showToast("拨打视频电话被接听")
            }
            Log.e("test",callOperationType.toString())
            ARouterHelper.navigateToLiveRoomActivity(this, LiveRoomBean(rtcToken = it.caller.rtcToken, userId = it.callee.uid, chatRoomId = it.chatRoomId, channelId = it.channelId, channelName = it.channelName, isIncoming = callOperationType == CallOperationType.INCOMING_VIDEO))
            finish() //拨打视频电话被接听 不需要发消息 和toast
        }else
        if (it is HangUpVideoReply) { //收到关闭通话消息 有可能是自己 关闭
            showToast(resources.getString(com.example.resources.R.string.call_now))


            onBackPressedCallback.handleOnBackPressed()
        }else
        if (it is MatchCancel) { //匹配取消 通话已经挂断 直接关闭就可  这里可能是呼叫失败 或者收到挂断推送
            showToast(resources.getString(com.example.resources.R.string.call_now))
            onBackPressedCallback.handleOnBackPressed()
        }else
        if (it is CallVideoReply) {//拨打电话回调 保存下房间号
            channelName = it.channelName
        }else
        if (it is Users) {//如果没有拿到相册或者只有uid情况
            it.apply {
                val userInfo = getString(com.example.resources.R.string.user_info_format, this.nickname, this.age)
                getViewBind().tvName.text = userInfo
                val imgMediaList = it.mediaList.toMutableList().filter { it.type.isTypeImg() }
                if (imgMediaList.isNotEmpty()) {
                    val randomImage = imgMediaList.random()
                    val imageView = ImageView(this@setModeView)
                    imageView.scaleType = ImageView.ScaleType.CENTER_CROP
//                    imageView.updateLayoutParams<ConstraintLayout.LayoutParams> {
//                        width = deviceSize.width
//                        height = deviceSize.height
//                    }
                    getViewBind().localVideoViewContainer.addView(imageView)
                    imageView.loadImageWithPlaceholderAndTransformation(randomImage.url, 5, 2)
                } else { // 如果没有图片可用，则执行相应的操作
                }

                val country = getCountryBean(countryCode)
                country?.let {
                    getViewBind().imCountry.loadImage(it.countryFlag)
                    getViewBind().tvLanguage.text = it.countryName
                }
            }
        }else
        if (it is CloseCallVideo) {
            finish()

        }else
        if (it is RefuseVideoReply) {//对方拒绝电话


            //showToast(resources.getString(com.example.resources.R.string.call_canceled))
            finish()
        }else
            if(it is GetChannelInfoReply){
                Log.e("tag  回到app ",it.channelName)
                if(TextUtils.isEmpty(it.channelName)){

                    finish()
                }
            }else if(it is VideoCallEndReasonBean){//视频被拒绝
                callVideoReply?.apply {
                    AgoraClient.getInstance().sendImCallMsg(user.uid.toString())
                }
                showToast(resources.getString(com.example.resources.R.string.call_now))
                onBackPressedCallback.handleOnBackPressed()
            }else if(it is GetAlbumReply){
            if(it.mediaList.size!=0){
                val ringList = it.mediaList.toMutableList().filter { it.isRing == 1 }
                if(ringList.isNotEmpty()){

                    playVideo(ringList[0].url)
                }else{
                    val videoList = it.mediaList.toMutableList().filter { !it.type.isTypeImg() }
                    if(videoList.isNotEmpty()){

                        playVideo(videoList[0].url)
                    }else{
                        val imgMediaList = it.mediaList.toMutableList().filter { it.type.isTypeImg() }
                        if (imgMediaList.isNotEmpty()) {

                            val randomImage = imgMediaList.random()
                            val imageView = ImageView(this)
                            imageView.scaleType = ImageView.ScaleType.CENTER_CROP
                            getViewBind().localVideoViewContainer.addView(imageView)
                            imageView.loadImageWithPlaceholderAndTransformation(randomImage.url, 5, 2)
                        }else{

                        }
                    }

                }

            }
        }else if(it is CallCancel){
                showToast(resources.getString(com.example.resources.R.string.call_now))
                finish()
        }
    }
}
